package com.xbongbong.paas.service.dynamic.help;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormEntity;
import com.xbongbong.paas.service.dynamic.crm.strategy.AbstractDynamicStrategy;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.pro.customercommunicate.pojo.dto.DynamicDTO;
import com.xbongbong.saas.enums.ProjectLogEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author lzf
 * @date 2022/4/20 9:46
 * 动态详情helper
 */
@Component
public class DynamicDetailsHelper extends AbstractDynamicStrategy {

    private final Logger LOG = LoggerFactory.getLogger(DynamicDetailsHelper.class);

    @Override
    @Async("dynamicThreadPool")
    public void insertDynamic(List<DynamicDTO> list, String corpid) {
        try {
            super.insertDynamic(list, corpid);
        } catch (Exception e) {
            LOG.error("com.xbongbong.paas.service.dynamic.help.DynamicDetailsHelper.insertDynamic", e);
        }
    }

    @Override
    @Async("dynamicThreadPool")
    protected void insertSimpleDynamic(List<DynamicDTO> list, String corpid) {
        try {
            super.insertSimpleDynamic(list, corpid);
        }catch (Exception e){
            LOG.error("com.xbongbong.paas.service.dynamic.help.DynamicDetailsHelper.insertDynamic", e);
        }
    }

    @Async("dynamicThreadPool")
    public void insertDynamic(List<DynamicDTO> list, String corpid, Integer businessType, JSONObject data) {
        try {
            List<DynamicDTO> insertDynamics = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            if (Objects.nonNull(data) && CollectionUtils.isNotEmpty(list)) {
                Map<String, Integer> refTextToLogTypeMap = getRefTextToLogTypeMap(businessType);
                for (DynamicDTO dto : list) {
                    List<Long> contactIds = null;
                    List<Long> opportunityIds = null;
                    List<Long> contractIds = null;
                    Long customerId = null;
                    for (Map.Entry<String, Integer> entry : refTextToLogTypeMap.entrySet()) {
                        Integer logType = entry.getValue();
                        String refText = entry.getKey();
                        XbbRefTypeEnum xbbRefTypeEnum = ProjectLogEnum.getBusinessTypeBySubType(logType);
                        switch (xbbRefTypeEnum) {
                            case CUSTOMER_MANAGEMENT:
                                dto.setCustomerId(null);
                                customerId = FastJsonHelper.getLongFromFormData(data, refText);
                                break;
                            case CONTACT:
                                dto.setContactId(null);
                                contactIds = FastJsonHelper.getTransferTypesFromData(data, refText, Long.class);
                                break;
                            case SALES_OPPORTUNITY:
                                dto.setOpportunityId(null);
                                opportunityIds = FastJsonHelper.getTransferTypesFromData(data, refText, Long.class);
                                break;
                            case CONTRACT:
                                dto.setContractId(null);
                                contractIds = FastJsonHelper.getTransferTypesFromData(data, refText, Long.class);
                                break;
                            default:
                                break;
                        }
                    }
                    try {
                        DynamicDTO dynamicDTO = BeanUtil.copyProperties(dto, DynamicDTO.class, true);
                        dynamicDTO.setCustomerId(null);
                        dynamicDTO.setContractId(null);
                        dynamicDTO.setOpportunityId(null);
                        dynamicDTO.setContactId(null);
                        List<DynamicDTO> dynamicDTOS = settingRefIdToDynamicDto(dynamicDTO, contactIds, contractIds, opportunityIds);
                        if (CollectionUtils.isNotEmpty(dynamicDTOS)) {
                            DynamicDTO firstDto = dynamicDTOS.get(0);
                            firstDto.setCustomerId(customerId);
                            BeanUtil.copyProperties(dto, firstDto, true);
                            insertDynamics.addAll(dynamicDTOS);
                        } else {
                            // 走到这里就知道当前dto最多有个客户上游
                            if(Objects.nonNull(customerId)) {
                                dto.setCustomerId(customerId);
                                insertDynamics.add(dto);
                            }
                        }
                    } catch (Exception e) {
                        LOG.error("com.xbongbong.paas.service.dynamic.help.DynamicDetailsHelper.settingRefIdToDynamicDto调用失败：", e);
                    }
                }
            }
            insertDynamic(insertDynamics, corpid);
        } catch (Exception e) {
            LOG.error("com.xbongbong.paas.service.dynamic.help.DynamicDetailsHelper.insertDynamic02", e);
        }
    }

    public List<DynamicDTO> settingRefIdToDynamicDto(DynamicDTO dynamicDTO, List<Long> contactIds, List<Long> contractIds, List<Long> opprtunityIds) throws XbbException {
        List<DynamicDTO> insertDynamicDTOS = new ArrayList<>();
        // 联系人
        if (CollectionUtils.isNotEmpty(contactIds)) {
            for (Long contactId : contactIds) {
                if (Objects.nonNull(contactId) && contactId != 0L) {
                    DynamicDTO dto = BeanUtil.copyProperties(dynamicDTO, DynamicDTO.class, true);
                    dto.setContactId(contactId);
                    insertDynamicDTOS.add(dto);
                }
            }
        }
        // 合同
        List<DynamicDTO> dynamicContractDTOS = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(contractIds)) {
            for (Long contractId : contractIds) {
                if (Objects.nonNull(contractId) && contractId != 0L) {
                    boolean newDynamic = true;
                    for (DynamicDTO dto : insertDynamicDTOS) {
                        if (Objects.isNull(dto.getContractId())) {
                            dto.setContractId(contractId);
                            newDynamic = false;
                            break;
                        }
                    }
                    if (newDynamic) {
                        DynamicDTO dto = BeanUtil.copyProperties(dynamicDTO, DynamicDTO.class, true);
                        dto.setContractId(contractId);
                        dynamicContractDTOS.add(dto);
                    }
                }
            }
        }
        insertDynamicDTOS.addAll(dynamicContractDTOS);
        // 机会
        List<DynamicDTO> dynamicOppDTOS = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(opprtunityIds)) {
            for (Long opprtunityId : opprtunityIds) {
                if (Objects.nonNull(opprtunityId) && opprtunityId != 0L) {
                    boolean newDynamic = true;
                    for (DynamicDTO dto : insertDynamicDTOS) {
                        if (Objects.isNull(dto.getOpportunityId())) {
                            dto.setOpportunityId(opprtunityId);
                            newDynamic = false;
                            break;
                        }
                    }
                    if (newDynamic) {
                        DynamicDTO dto = BeanUtil.copyProperties(dynamicDTO, DynamicDTO.class, true);
                        dto.setOpportunityId(opprtunityId);
                        dynamicOppDTOS.add(dto);
                    }
                }
            }
        }
        insertDynamicDTOS.addAll(dynamicOppDTOS);
        return insertDynamicDTOS;
    }

    /**
     * 获取表单信息
     * @param corpid
     * @param formId
     * @param businessType
     * @return
     */
    @Override
    public PaasFormEntity getPaasForm(String corpid, Long formId, Integer businessType) {
        return super.getPaasForm(corpid, formId, businessType);
    }

    @Override
    public DynamicDTO initDynamicDTO(String creatorId, String memo, Integer logType, List<String> memoPlaceHolder, PaasFormEntity paasFormEntity, Integer saasMark, Long dataId) {
        return super.initDynamicDTO(creatorId, memo, logType, memoPlaceHolder, paasFormEntity, saasMark, dataId);
    }

}
